package cn.iocoder.springboot.lab03.kafkademo.aspect;

import cn.iocoder.springboot.lab03.kafkademo.constant.Constants;
import cn.iocoder.springboot.lab03.kafkademo.utils.MD5Utils;
import cn.iocoder.springboot.lab03.kafkademo.utils.RequestUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author：YH
 * @Description：
 * @Date:Created in 2023/12/30 23:36
 */
@Aspect
@Component
public class RequestLogAspect {

    private static final Logger LOG = LoggerFactory.getLogger(RequestLogAspect.class);
    /**
     * Publish config.
     */
    private static final String CLIENT_INTERFACE_PUBLISH_SINGLE_CONFIG =
            "execution(* cn.iocoder.springboot.lab03.kafkademo.controller.ControllerTest.publishConfig(..)) && args"
                    + "(request,response,dataId,group,tenant,content,..)";

    /**
     * PublishSingle.
     */
    @Around(CLIENT_INTERFACE_PUBLISH_SINGLE_CONFIG)
    public Object interfacePublishSingle(ProceedingJoinPoint pjp, HttpServletRequest request,
                                         HttpServletResponse response, String dataId, String group, String tenant,
                                         String content) throws Throwable {
        final String md5 = content == null ? null : MD5Utils.md5Hex(content, Constants.ENCODE);
        //MetricsMonitor.getPublishMonitor().incrementAndGet();
        return logClientRequest("publish", pjp, request, response, dataId, group, tenant, md5);
    }

    private Object logClientRequest(String requestType, ProceedingJoinPoint pjp, HttpServletRequest request,
                                    HttpServletResponse response, String dataId, String group, String tenant,
                                    String md5) throws Throwable {
        final String requestIp = RequestUtil.getRemoteIp(request);
        String appName = request.getHeader(RequestUtil.CLIENT_APPNAME_HEADER);
        final long st = System.currentTimeMillis();
        Object retVal = pjp.proceed();
        final long rt = System.currentTimeMillis() - st;
        // rt | status | requestIp | opType | dataId | group | datumId | md5 |
        // appName
        LOG.info("{}|{}|{}|{}|{}|{}|{}|{}|{}", rt, retVal, requestIp, requestType, dataId, group, tenant, md5,
                appName);
        return retVal;
    }
}
